import 'package:flutter/material.dart';

class ListViewHomePage extends StatefulWidget {
  @override
  _ListViewHomePageState createState() => _ListViewHomePageState();
}

class _ListViewHomePageState extends State<ListViewHomePage> {
  bool select = false;
  List list = [];
  ScrollController scrollController = new ScrollController();
  num offset = 0;
  IconData iconData = Icons.home;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    for (int i = 0; i < 20; i++) {
      list.add("list $i");
    }
    scrollController.addListener(() {
      // offset ：listview与顶部的距离
      setState(() {
        offset = scrollController.offset;
      });
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        loadMore();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    print(offset);
    if (offset > 200) {
      iconData = Icons.arrow_upward;
    } else {
      iconData = Icons.home;
    }
    setState(() {});
    return Scaffold(
      appBar: AppBar(
        title: Text("listview配置"),
      ),
      floatingActionButton: FloatingActionButton(
          onPressed: () {
            scrollController.animateTo(0,
                duration: new Duration(milliseconds: 1000), curve: Curves.ease);
          },
          child: Icon(iconData)),
      // 线性布局  构建分割线
      body: RefreshIndicator(
        // 刷新组件圆圈 距离顶部的距离
        // displacement: 100, //默认40

        // 刷新组件圆圈 的颜色
        // color: Colors.red,
        // 刷新组件圆圈 的背景颜色
        // backgroundColor: Colors.green,
        child: buildListView(),
        onRefresh: onRefresh,
      ),
    );
  }

  // 下拉刷新事件
  Future<void> onRefresh() async {
    print("开始下拉刷新");

    await Future.delayed(Duration(milliseconds: 3000), () {
      print("结束下拉刷新");
      list.clear();
      for (int i = 0; i < 20; i++) {
        list.add("下拉刷新数据 $i");
      }
      setState(() {});
    });
  }

  // 构建list列表
  Widget buildListView() {
    return ListView.separated(
      controller: scrollController,
      physics: BouncingScrollPhysics(),
      separatorBuilder: (BuildContext context, num index) {
        return Container(
            height: 2, color: index % 2 == 0 ? Colors.red : Colors.green);
      },
      itemBuilder: (BuildContext context, num index) {
        if (list.length == index) {
          return Container(
              width: 80,
              height: 80,
              alignment: Alignment.center,
              child: Text("加载更多", style: TextStyle(color: Colors.white)),
              color: Colors.grey);
        }
        return Container(
            width: 80,
            height: 80,
            child: Text(list[index]),
            color: Colors.grey);
      },
      itemCount: list.length + 1,
    );
  }

  // 上拉加载
  void loadMore() {
    for (int i = 0; i < 20; i++) {
      list.add("上拉加载数据 $i");
    }
    setState(() {});
  }
}
